package com.qf.controller;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.bean.JsonResult;
import com.qf.pojo.Goods;
import com.qf.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;
    private String uploadFileName;
    @RequestMapping("findByPageGoods")
    public JsonResult findByPage(@RequestParam(value = "page",required = false,defaultValue = "1")Integer pageNum,
                                 @RequestParam(value = "limit",required = false,defaultValue = "2")Integer pageSize){
        PageHelper.startPage(pageNum,pageSize);
        List<Goods> goodsList = goodsService.findAll();
        PageInfo<Goods> pageInfo = new PageInfo<>(goodsList);

        JsonResult jsonResult = JsonResult.ok();
        jsonResult.setCount(pageInfo.getTotal());
        jsonResult.setData(pageInfo.getList());
        return jsonResult;
    }

    @RequestMapping("deleteByIdGoods")
    public String deleteById(Integer id){
        System.out.println(id);
        goodsService.deleteById(id);
        return "success";
    }
    @RequestMapping("updateByGoods")
    public String updateGoods(Goods goods){
        goodsService.updateGoods(goods);
        return "success";
    }

    @RequestMapping("uploadPic")
    public JsonResult upload1(MultipartFile file){
        //上传的原文件名
        uploadFileName = file.getOriginalFilename();
        //使用UUID声明前缀，防止上传的图片名重复
        uploadFileName = UUID.randomUUID().toString().replace("-","")+uploadFileName;
        //声明上传的路径
        String uploadPath = "F:\\QF\\apache-tomcat-8.5.31-windows-64位\\apache-tomcat-8.5.31\\webapps\\guimei\\";
        try {
            //上传
            file.transferTo(new File(uploadPath,uploadFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        JsonResult jsonResult = JsonResult.ok();
        jsonResult.setMsg("http://localhost:8088/guimei/"+uploadFileName);
        return jsonResult;
    }

    @RequestMapping("findAllType")
    public List<Goods> findAllType(){
        List<Goods> goods = goodsService.findAllType();
        return goods;
    }
    @RequestMapping("addByGoods")
    public String addByGoods(Goods goods){
        goods.setPicture("http://localhost:8088/guimei/"+uploadFileName);
        System.out.println("====="+goods);
        goodsService.addByGoods(goods);
        return "success";
    }



}
